package com.google.appengine.a4ieve.servlets.resources;

import com.google.appengine.a4ieve.Const;
import com.google.appengine.a4ieve.Helper;
import com.google.appengine.a4ieve.entities.CuratorWrapper;
import com.google.appengine.api.datastore.*;
import org.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;

/**
 * User: lunin
 * Date: 4/22/14
 * Time: 5:40 PM
 */
class GetCuratorServant implements Servant {

    private static final Logger LOG = Logger.getLogger(GetCuratorServant.class.getName());

    @Override
    public void process(HttpServletRequest req, HttpServletResponse resp) {
        DatastoreService store = DatastoreServiceFactory.getDatastoreService();
        JSONObject requestJson = (JSONObject) req.getAttribute(Const.INNER_JSON);
        int page = Integer.parseInt((String) requestJson.get(Const.PAGE));
        int count = Integer.parseInt((String) requestJson.get(Const.COUNT));
        List<Entity> curatorEntities = new LinkedList<Entity>();
        Query curatorQuery = new Query(CuratorWrapper.KIND_KEY).addSort(CuratorWrapper.USER_ID_PROPERTY).setKeysOnly();
        curatorEntities = store.prepare(curatorQuery).asList(FetchOptions.Builder.withOffset((page - 1) * count).limit(count));
        Query totalCountQuery = new Query(CuratorWrapper.KIND_KEY);
        int total = store.prepare(totalCountQuery).countEntities(FetchOptions.Builder.withDefaults());
        try {
            Helper.writeEntitiesToJson(CuratorWrapper.class, curatorEntities, total, store).write(resp.getWriter());
        } catch (IOException i) {
            LOG.severe("Error while writing curator information " + i);
        }
    }
}
